/**
 * Alpha优先透明效果测试工具
 * 用于测试和验证alpha值优先的透明材质效果
 */

export class AlphaTransparencyTester {
    constructor() {
        this.testResults = [];
    }

    /**
     * 测试场景中所有透明材质的alpha优先效果
     */
    testAllTransparentMaterials() {
        console.log('🧪 [Alpha透明测试] 开始测试场景中的透明材质...');
        
        const scene = window.scene;
        if (!scene) {
            console.error('❌ 无法获取场景对象');
            return;
        }

        this.testResults = [];
        let materialCount = 0;
        let transparentCount = 0;

        scene.traverse((object) => {
            if (object.isMesh && object.material) {
                const materials = Array.isArray(object.material) ? object.material : [object.material];
                
                materials.forEach((material, index) => {
                    materialCount++;
                    const materialName = material.name || `Material_${materialCount}`;
                    
                    // 检查是否为透明材质
                    const isTransparent = this.isTransparentMaterial(material);
                    
                    if (isTransparent) {
                        transparentCount++;
                        const testResult = this.testMaterialTransparency(material, materialName, object.name);
                        this.testResults.push(testResult);
                        
                        console.log(`🔍 [透明材质] ${materialName}:`, testResult);
                    }
                });
            }
        });

        console.log(`✅ 透明材质测试完成: 总材质${materialCount}个，透明材质${transparentCount}个`);
        return this.testResults;
    }

    /**
     * 检查材质是否为透明材质
     */
    isTransparentMaterial(material) {
        return material.transparent || 
               material.alphaTest > 0 || 
               material.opacity < 1 ||
               !!material.alphaMap;
    }

    /**
     * 测试单个材质的透明效果
     */
    testMaterialTransparency(material, materialName, objectName) {
        const result = {
            materialName,
            objectName,
            透明类型: this.getTransparencyType(material),
            基础颜色: `RGB(${material.color.r.toFixed(3)}, ${material.color.g.toFixed(3)}, ${material.color.b.toFixed(3)})`,
            opacity: material.opacity,
            alphaTest: material.alphaTest,
            transparent: material.transparent,
            depthWrite: material.depthWrite,
            hasMap: !!material.map,
            hasAlphaMap: !!material.alphaMap,
            alpha优先策略: this.checkAlphaPriorityStrategy(material),
            建议优化: this.getSuggestions(material)
        };

        return result;
    }

    /**
     * 获取透明类型
     */
    getTransparencyType(material) {
        if (material.opacity < 1) {
            return 'opacity透明';
        } else if (material.alphaTest > 0) {
            return 'alphaTest硬边透明';
        } else if (material.transparent) {
            return 'transparent模式';
        } else if (material.alphaMap) {
            return 'alphaMap透明';
        }
        return '未知透明类型';
    }

    /**
     * 检查是否符合alpha优先策略
     */
    checkAlphaPriorityStrategy(material) {
        const hasAlpha = material.opacity < 1 || material.alphaTest > 0 || material.alphaMap;
        const hasWhiteBase = material.color.r >= 0.9 && material.color.g >= 0.9 && material.color.b >= 0.9;
        
        if (hasAlpha && hasWhiteBase) {
            return '✅ 符合alpha优先策略';
        } else if (hasAlpha && !hasWhiteBase) {
            return '⚠️ 有alpha但基础颜色非白色';
        } else {
            return '❌ 非alpha透明材质';
        }
    }

    /**
     * 获取优化建议
     */
    getSuggestions(material) {
        const suggestions = [];
        
        // 检查基础颜色
        const hasAlpha = material.opacity < 1 || material.alphaTest > 0 || material.alphaMap;
        const isDarkColor = material.color.r < 0.5 || material.color.g < 0.5 || material.color.b < 0.5;
        
        if (hasAlpha && isDarkColor) {
            suggestions.push('建议将基础颜色设为白色，让alpha通道主导');
        }

        // 检查透明模式冲突
        if (material.transparent && material.alphaTest > 0) {
            suggestions.push('transparent和alphaTest冲突，建议选择其一');
        }

        // 检查深度写入设置
        if (material.transparent && material.depthWrite) {
            suggestions.push('transparent模式建议禁用depthWrite');
        }

        if (material.alphaTest > 0 && !material.depthWrite) {
            suggestions.push('alphaTest模式建议启用depthWrite');
        }

        return suggestions.length > 0 ? suggestions : ['无需优化'];
    }

    /**
     * 应用alpha优先策略到所有透明材质
     */
    applyAlphaPriorityToAll() {
        console.log('🔧 [Alpha优先修复] 开始应用alpha优先策略...');
        
        const scene = window.scene;
        if (!scene) {
            console.error('❌ 无法获取场景对象');
            return;
        }

        let fixedCount = 0;

        scene.traverse((object) => {
            if (object.isMesh && object.material) {
                const materials = Array.isArray(object.material) ? object.material : [object.material];
                
                materials.forEach((material) => {
                    if (this.isTransparentMaterial(material)) {
                        this.applyAlphaPriorityStrategy(material);
                        fixedCount++;
                    }
                });
            }
        });

        console.log(`✅ Alpha优先策略应用完成，修复了${fixedCount}个透明材质`);
        return fixedCount;
    }

    /**
     * 应用alpha优先策略到单个材质
     */
    applyAlphaPriorityStrategy(material) {
        const materialName = material.name || 'Unknown';
        console.log(`🔧 [Alpha优先修复] 修复材质: ${materialName}`);

        // 检查是否有alpha透明设置
        const hasAlpha = material.opacity < 1 || material.alphaTest > 0 || material.alphaMap;
        
        if (hasAlpha) {
            // 🔑 关键策略：基础颜色设为白色，让alpha通道主导
            material.color.setRGB(1.0, 1.0, 1.0);
            
            if (material.opacity < 1) {
                // opacity透明模式
                material.transparent = true;
                material.alphaTest = 0;
                material.depthWrite = false;
                material.depthTest = true;
                console.log(`   🔧 opacity透明模式：opacity=${material.opacity}`);
                
            } else if (material.alphaTest > 0) {
                // alphaTest透明模式
                material.transparent = false;
                material.depthWrite = true;
                material.depthTest = true;
                console.log(`   🔧 alphaTest透明模式：alphaTest=${material.alphaTest}`);
                
            } else if (material.alphaMap) {
                // alphaMap透明模式
                material.transparent = true;
                material.alphaTest = 0;
                material.depthWrite = false;
                material.depthTest = true;
                console.log(`   🔧 alphaMap透明模式`);
            }
            
            material.needsUpdate = true;
            console.log(`   ✅ Alpha优先策略应用完成`);
        }
    }

    /**
     * 生成测试报告
     */
    generateReport() {
        if (this.testResults.length === 0) {
            console.log('📋 暂无测试结果，请先运行测试');
            return;
        }

        console.log('📋 ========== Alpha透明材质测试报告 ==========');
        console.log(`总透明材质数量: ${this.testResults.length}`);
        
        const strategyStats = {
            '✅ 符合alpha优先策略': 0,
            '⚠️ 有alpha但基础颜色非白色': 0,
            '❌ 非alpha透明材质': 0
        };

        this.testResults.forEach((result, index) => {
            console.log(`\n${index + 1}. ${result.materialName} (${result.objectName})`);
            console.log(`   透明类型: ${result.透明类型}`);
            console.log(`   基础颜色: ${result.基础颜色}`);
            console.log(`   Alpha优先策略: ${result.alpha优先策略}`);
            console.log(`   建议优化: ${result.建议优化.join('; ')}`);
            
            strategyStats[result.alpha优先策略]++;
        });

        console.log('\n📊 策略符合度统计:');
        Object.entries(strategyStats).forEach(([key, value]) => {
            console.log(`   ${key}: ${value}个`);
        });

        console.log('==========================================');
    }
}

// 创建全局实例
const alphaTransparencyTester = new AlphaTransparencyTester();

// 暴露到全局
window.alphaTransparencyTester = alphaTransparencyTester;

// 便捷方法
window.testAlphaTransparency = () => alphaTransparencyTester.testAllTransparentMaterials();
window.fixAlphaTransparency = () => alphaTransparencyTester.applyAlphaPriorityToAll();
window.reportAlphaTransparency = () => alphaTransparencyTester.generateReport();

// console.log('🧪 Alpha透明测试工具已加载');
// console.log('   使用方法:');
// console.log('   - testAlphaTransparency()  // 测试所有透明材质');
// console.log('   - fixAlphaTransparency()   // 应用alpha优先策略');
// console.log('   - reportAlphaTransparency() // 生成测试报告');
